/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.bricket.web;

import org.apache.wicket.extensions.markup.html.captcha.CaptchaImageResource;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.util.value.ValueMap;

public class CaptchaPanel extends Panel {
    private static int randomInt(int min, int max) {
        return (int)(Math.random() * (max - min) + min);
    }
    
    private static String randomString(int min, int max) {
        int num = randomInt(min, max);
        byte b[] = new byte[num];
        for (int i = 0; i < num; i++) {
            b[i] = (byte)randomInt('a', 'z');
        }
        return new String(b);
    }

    /** Random captcha password to match against. */
    private final String imagePass = randomString(6, 8);
    
    private final ValueMap properties = new ValueMap();

    public CaptchaPanel(String id) {
		super(id);

		StringResourceModel lCaptcha = new StringResourceModel("captcha.label", CaptchaPanel.this, null);
		add(new Label("captcha.label", lCaptcha));
		CaptchaImageResource captchaImageResource = new CaptchaImageResource(imagePass);
	    add(new Image("captchaImage", captchaImageResource));
        add(new RequiredTextField<String>("captcha", new PropertyModel<String>(properties, "captcha"), String.class) {
            @Override
            protected final void onComponentTag(final ComponentTag tag) {
                super.onComponentTag(tag);
                // clear the field after each render
                tag.put("value", "");
            }
        });
	}

	public boolean isCaptchaValid() {
		return imagePass.equals(properties.getString("captcha"));
	}		
}